package cn.kgc.Adjudicative.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * <p>Project:Adjudicative_document
 * <p>Package:cn.kgc.Adjudicative.controller
 * <p>ClassName:CaptchaController
 * <p>Powered by sun On 2023-01-06  10:20:12
 *
 * @author 孙杰
 * @version 1.0
 * @Description:验证码
 * @date 2023/1/6 10:20
 * @since 11
 */
@RestController
public class CaptchaController {

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    private String captcha;

    public String getCaptcha() {
        return captcha;
    }

    public void setCaptcha(String captcha) {
        this.captcha = captcha;
    }

    @GetMapping(value = "/captcha",produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response){
        //定义response输出类型为image/jpeg
        response.setDateHeader("Expires",0);
        //Set standard HTTP/1.1 no-cache headers
        response.setHeader("Cache-Control","no-store,no-cache,must-revalidate");
        //Set IE extended HTTP/1.1 no-cache headers (use addHeader)
        response.addHeader("Cache-Control","post-check=0,pre-check=0");
        //Set standard HTTP/1.1 no-cache header
        response.setHeader("Pragma","no-cache");
        //return a jpeg
        response.setContentType("image/jpeg");
        //--------------------生成验证码begin-------------------
        //获取验证码文本内容
        String text = defaultKaptcha.createText();
        System.out.println("验证码内容："+text);
        //将验证码文本内容放入session
        request.getSession().setAttribute("captcha",text);
        this.setCaptcha(text);
        //根据文本验证码内容创建图形验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输入流输出图片，格式为jpg
            ImageIO.write(image,"jpg",outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (null != outputStream){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //--------------------生成验证码end---------------------

    }

}
